
/**
 * 根据后端数据流下载文件
 * @param {BlobPart} res 数据流
 * @param {string} filename 文件名
 * @param {BlobPropertyBag} BlobProperty
 */
function downloadResopnse(res, filename, BlobProperty = { type: 'application/vnd.ms-excel;charset=utf-8' }) {
  const blob = new Blob([res.data], BlobProperty) // 创建一个类文件对象：Blob对象表示一个不可变的、原始数据的类文件对象
  let download = ''
  if (!filename) {
    let reg = /filename=(.+);/
    filename = reg.exec(res.headers['content-disposition'])[1]
    download = decodeURIComponent(filename)
  } else {
    download = filename
  }
  downLoadURL(blob, download)
}

/**
* 根据地址下载文件
* @param {string} href
* @param {string} fileName
*/
function downLoadURL(href, fileName) {
  const elink = document.createElement('a')
  elink.download = fileName
  elink.style.display = 'none'
  if (href instanceof Blob) {
    elink.href = URL.createObjectURL(href)
  } else {
    elink.href = href
  }
  document.body.appendChild(elink)
  elink.click()
  URL.revokeObjectURL(elink.href) // 释放URL 对象
  document.body.removeChild(elink)
}

module.exports = {
  downLoadURL,
  downloadResopnse
}
